package com.hcloud.system.role.controller;

import com.hcloud.common.core.annontion.AuthPrefix;
import com.hcloud.common.core.annontion.OperateLog;
import com.hcloud.common.core.annontion.OperatePostfix;
import com.hcloud.common.core.base.HCloudResult;
import com.hcloud.common.core.constants.AuthConstants;
import com.hcloud.common.core.constants.OperateType;
import com.hcloud.common.crud.annon.HCloudPreAuthorize;
import com.hcloud.common.crud.controller.BaseDataController;
import com.hcloud.common.crud.service.BaseDataService;
import com.hcloud.system.role.entity.RoleAuthEntity;
import com.hcloud.system.role.entity.RoleEntity;
import com.hcloud.system.role.service.RoleService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 角色管理
 *
 * @Auther hepangui
 * @Date 2018/11/5
 */
@RestController
@RequestMapping("/role")
@AllArgsConstructor
@AuthPrefix(AuthConstants.SYSTEM_ROLE_PREFIX)
@OperatePostfix("角色")
public class RoleController extends BaseDataController<RoleEntity> {
    private final RoleService roleService;


    @Override
    public BaseDataService getBaseDataService() {
        return roleService;
    }

    /**
     * 根据角色id获取包含的权限
     *
     * @param roleId
     * @return
     */
    @PostMapping("authList")
    public HCloudResult<RoleAuthEntity> authList(String roleId) {
        List<RoleAuthEntity> roleAuthEntityByRoleId = roleService.findRoleAuthEntityByRoleId(roleId);
        return new HCloudResult(roleAuthEntityByRoleId);
    }

    @PostMapping("saveAuth")
    @HCloudPreAuthorize(AuthConstants.EDIT)
    @OperateLog(type = OperateType.UPDATE, title = "权限分配")
    public HCloudResult saveAuth(String roleId, String ids) {
        if (roleId == null || "".equals(roleId)) {
            return new HCloudResult("角色不能为空");
        }
        if (ids != null && !"".equals(ids)) {
            this.roleService.saveAuth(roleId, ids);
            return new HCloudResult();
        } else {
            return new HCloudResult("权限不可为空");
        }
    }

    /**
     * 主要用于登录时的认证调取
     *
     * @param roleIds
     * @return
     */
    @PostMapping("findAuthorityByRoleIds")
    public HCloudResult<List<String>> findByRoleIds(@RequestParam("roleIds") String roleIds) {
        if (roleIds == null || "".equals(roleIds)) {
            return new HCloudResult("roleId不能为空");
        }
        return new HCloudResult(this.roleService.findAuthorityByRoleIds(Arrays.asList(roleIds.split(","))));

    }

    @OperateLog(title = "删除角色", type = OperateType.DEL)
    @HCloudPreAuthorize(AuthConstants.DEL)
    @DeleteMapping("delete/{id}")
    @Override
    public HCloudResult deleteOne(@PathVariable String id) {
        this.roleService.deleteOne(id);
        return new HCloudResult();
    }
}
